package com.xiaouyudeguang.common.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class FileUtils {

    private static final Map<String, String> fileCtxCache = new ConcurrentHashMap<>();

    public static String getResource(String fileName) throws Exception {
        URL url = FileUtils.class.getClassLoader().getResource(fileName);
        if (url == null) {
            return null;
        }
        return getResource(new File(url.getFile()));
    }

    public static String getResource(File file) {
        String fileCtx = fileCtxCache.get(file.getName());
        if (StringUtils.isBlank(fileCtx)) {
            FileReader fileReader = null;
            Reader reader = null;
            try {
                fileReader = new FileReader(file);
                reader = new InputStreamReader(Files.newInputStream(file.toPath()), StandardCharsets.UTF_8);
                int ch;
                StringBuilder sb = new StringBuilder();
                while ((ch = reader.read()) != -1) {
                    sb.append((char) ch);
                }
                fileReader.close();
                reader.close();
                fileCtx = sb.toString();
                fileCtxCache.put(file.getName(), fileCtx);
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            } finally {
                if (fileReader != null) {
                    try {
                        fileReader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return fileCtx;
    }
}
